package com.quest.interrupt;

/**
 *@Description: 自定义标志位中断线程（不安全）
 */
public class FlagCancel {
    private static volatile boolean on = true;
    private static class ConsumeInterrupt implements Runnable{
        private long i = 0;

        @Override
        public void run() {
            while (on) {
                i++;
                try {
                    Thread.sleep(20000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void cancel(){
            on = false;
        }
    }

    private static class BlockInterrupt implements Runnable {

        @Override
        public void run() {
            while (on && !Thread.currentThread().isInterrupted()) {
                try {
                    //抛出中断异常的阻塞方法，抛出异常后，中断标志位改成false
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();//重新设置一下
                    //do my work
                }
                //清理工作结束线程
            }
        }

        public void cancel() {
            on = false;
            Thread.currentThread().interrupt();
        }

    }

}
